<!--这是试卷专题 增加编辑组件-->
<template>
  <div class="app-container">
    <el-form :model="postForm" v-loading="formLoading" :rules="rules" ref="postForm" label-width="220px"
             label-position="right">
      <p class="font-family-h font-bold margin-t50 margin-b40"><i class="square"></i>基础资料</p>
      <el-form-item label="试卷专题名称：" prop="name">
        <el-input :maxlength=26 v-model="postForm.name" placeholder="请输入试卷专题名称" style="width: 650px"></el-input>
      </el-form-item>
       <!-- <el-form-item label="试卷专题图片(宽120*高120)：">
       <el-upload
          ref="avatarUpload"
          name="avatar"
          :action="imageUploadUrl"
          list-type="picture"
          :before-upload="handleBeforeUpload"
          :on-success="handleAvatarSuccess"
          :on-remove="handleAvatarRemove"
          :file-list="avatarList"
          :limit="1"
          :auto-upload="false"
          style="width: 420px">
          <el-button slot="trigger" size="small" type="primary" @click="beforeChoose">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitAvatarUpload">上传到服务器
          </el-button>
        </el-upload>
      </el-form-item> -->
      <!-- <el-form-item label="试卷专题图片(宽120*高120)：">
        <image-component class="fl" :image="postForm.avatar" :width="'120px'" :height="'120px'"></image-component>
        <el-button  class="fl" type="primary" icon="upload" style="bottom: 15px;margin-left: 40px;" @click="imagecropperShow=true">
          更换图片
        </el-button>
        <image-cropper :width="640" :height="640" :url="imageUploadUrl" @close='closeImageCropper'
                      @crop-upload-success="cropSuccess" langType="zh"
                      :key="imagecropperKey" v-show="imagecropperShow"></image-cropper>
      </el-form-item> -->
      <el-form-item label="试卷专题图片(宽120*高120)：">
        <div class="clearfix">
          <img class="fl margin-r" :src="postForm.avatar" @error="setDefultImg" width="180" height="120" alt="">
          <el-upload
            class="fl"
            ref="avatarUpload"
            name="avatar"
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            :auto-upload="true"
            style="width: 420px">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3m</div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input type="number" min="0"  v-model="postForm.sort" placeholder="请输入排序" class="width110"></el-input>
      </el-form-item>
      <el-form-item label="测评完成是否显示答案解析：">
        <el-radio-group v-model="postForm.isShowResult">
          <el-radio :label="-1">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="价格：" prop="price">
        <el-input min="0" type="number" v-model="postForm.price" placeholder="请输入价格" class="width110"></el-input>元
      </el-form-item>
      <el-form-item label="vip折扣：" prop="vipDiscount">
        <el-input min="0" type="number" v-model="postForm.vipDiscount" class="width110"></el-input>
        %
        <span class="point">注意：会员以上级别购买才可参与折扣。票价 * 比例 = 当前价格。例如 75% 同于 7.5 折，0% 即票价免费。系统默认初始化 100%</span>
      </el-form-item>
      <el-form-item label="svip折扣：" prop="svipDiscount" v-if="this.enableSvip">
        <el-input min="0" type="number" v-model="postForm.svipDiscount" class="width110"></el-input>
        %<span></span>
      </el-form-item>
      <el-form-item label="是否开通邀请卡：">
        <el-radio-group v-model="postForm.isInvitationCard">
          <el-radio :label="-1">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="邀请后可优惠：">
    <el-input v-model="postForm.deductibleAfterInvition" ></el-input>
  </el-form-item> -->

      <el-form-item label="专题简介：">
        <tinymce :height="300" v-model="postForm.contact"></tinymce>
      </el-form-item>

      <p class="font-family-h font-bold margin-t50 margin-b40"><i class="square"></i>抽成设置<span class="point">(抽成比例总和勿大于100%，即:讲师抽成比例+一级抽成比例+二级抽成比例+三级抽成比例+代理商抽成比例+合伙人抽成比例+分公司抽成比例小于等于100%)</span>
      </p>
      <!--<el-form-item label="是否关联讲师：">-->
        <!--<el-select v-model="postForm.hasteacher" placeholder="请选择" style="width: 650px" @change="isTeacherSelect">-->
          <!--<el-option v-for="item in isTeacherOptions" :key="item.key" :label="item.value" :value="item.key"></el-option>-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item label="是否关联收益人：">
        <el-radio-group v-model="postForm.hasteacher">
          <el-radio :label="-1">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择收益人：" v-show="postForm.hasteacher==1">

        <multiselect style='width:500px;' v-model="teacherInfo" :options="teacherList" track-by="userId"
                     label="nickname"
                     placeholder="搜索收益人" selectLabel="选择" deselectLabel="删除" @select="teacherOptionSelect"
                     @search-change="syncSearchTeachers" :internalSearch="false">
          <span slot='noResult'>无结果</span>
        </multiselect>

      </el-form-item>
      <el-form-item label="收益人抽成比例(单位%)：" v-show="postForm.hasteacher==1" prop="teaRate">
        <el-input v-model="postForm.teaRate" type='number' placeholder="收益人抽成比例" class="width110"></el-input>
      </el-form-item>
      <el-form-item label="第一级别抽成(单位%)：">
        <el-table :data="stage1" border style="width: 650px;">
          <el-table-column label="第一级抽成比例" prop="firstRate">
            <template slot-scope="scope">
              <el-input min="0" v-model="postForm.firstRate" type='number' placeholder="第一级抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="第二级抽成比例" prop='secondRate'>
            <template slot-scope="scope">
              <el-input min="0" v-model="postForm.secondRate" type='number' placeholder="请输入第二级抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="第三级抽成比例" prop="thirdRate">
            <template slot-scope="scope">
              <el-input min="0" v-model="postForm.thirdRate" type='number' placeholder="请输入第二级抽成比例"></el-input>
            </template>
          </el-table-column>
        </el-table>

      </el-form-item>

      <el-form-item label="服务商抽成比例(单位%)：" v-if="this.agentLevel > 0">
        <el-table :data="stage2" border style="width: 650px;">
          <el-table-column label="代理商抽成比例" prop="dlsRate">
            <template slot-scope="scope">
              <el-input min="0" v-model="postForm.dlsRate" type='number' placeholder="代理商抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="合伙人抽成比例" prop="partnerRate" v-if="this.agentLevel == 3">
            <template slot-scope="scope">
              <el-input min="0" v-model="postForm.partnerRate" type='number' placeholder="合伙人抽成比例"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="分公司抽成比例" prop="branchRate" v-if="this.agentLevel == 3">
            <template slot-scope="scope">
              <el-input min="0" v-model="postForm.branchRate" type='number' placeholder="分公司抽成比例"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <p class="font-family-h font-bold margin-t50 margin-b40"><i class="square"></i>分享设置</p>
     <!--<el-form-item label="分享公众号标题：" >-->
        <!--<el-input v-model="postForm.shareTitle" placeholder="请输入公众号标题" style="width: 650px"></el-input>-->
      <!--</el-form-item>-->
     <el-form-item label="分享公众号描述：" >
        <el-input :maxlength=29 v-model="postForm.shareDesc" placeholder="请输入描述，不超过29个字" style="width: 650px"></el-input>
      </el-form-item>
      <p class="font-family-h font-bold margin-t50 margin-b40"><i class="square"></i>上架设置</p>
      <el-form-item label="是否上架：">
        <el-radio-group v-model="postForm.isGrounding">
          <el-radio :label="-1">暂不上架-显示为(下架)状态</el-radio>
          <el-radio :label="1">立即上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-loading="btnLoading" icon="el-icon-check" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import Tinymce from '@/components/Tinymce'
  // import imageComponent from '@/components/imageComponent'
  // import ImageCropper from '@/components/ImageCropper'
  import { getTopicDetail, topicEditSave, getTheTea } from '@/api/topic'
  import { getMemberSearch, initMemberList } from '@/api/member'
  import { toGetCompanyInfo } from '@/api/common'
  import Multiselect from 'vue-multiselect' // 引入 vue-multiselect 组件
  import 'vue-multiselect/dist/vue-multiselect.min.css'
  import { validatePercent, validateNumber } from '@/utils/vm'
  import { enableSvip } from '@/utils/permission'
  import defultImg from '@/assets/defult270.png'
  const postForm = {
    topicId: '',
    name: '', // 名称
    avatar: '',
    price: 0, // 价格
    isShowResult: -1, // 测评完是否显示答案
    isGrounding: -1, // 是否上架
    sort: 0, // 排序
    vipDiscount: '100', // vip折扣比例
    svipDiscount: '100', // svip折扣比例
    hasteacher: -1, // 是否关联讲师
    teacherId: null, // 选择讲师
    teaRate: 0, // 讲师抽成比例
    firstRate: 0,
    secondRate: 0,
    thirdRate: 0,
    dlsRate: 0,
    partnerRate: 0,
    branchRate: 0,
    isInvitationCard: 1,
    deductibleAfterInvition: 0
  }

  export default {
    components: { Tinymce, Multiselect }, // 子主件
    props: {
      // 属性
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      // 数据
      return {
        postForm: Object.assign({}, postForm),
        agentLevel: 0,
        enableSvip: 1,
        rules: {
          name: [
            { required: true, message: '请输入试卷专题名称', trigger: 'blur' },
            { min: 0, max: 26, message: '长度在 0 到 26 个字符', trigger: 'blur' }
          ],
          sort: [{
            validator: validateNumber, trigger: 'blur'
          }],
          vipDiscount: [{
            validator: validatePercent, trigger: 'blur'
          }],
          svipDiscount: [{
            validator: validatePercent, trigger: 'blur'
          }],
          teaRate: [{
            validator: validatePercent, trigger: 'blur'
          }],
          price: [{
            required: true, validator: validateNumber, trigger: 'blur'
          }],
          firstRate: [
            { validator: validatePercent, trigger: 'submitForm' }
          ],
          secondRate: [
            { validator: validatePercent, trigger: 'submitForm' }
          ],
          thirdRate: [
            { validator: validatePercent, trigger: 'submitForm' }
          ],
          dlsRate: [
            { validator: validatePercent, trigger: 'submitForm' }
          ],
          partnerRate: [
            { validator: validatePercent, trigger: 'submitForm' }
          ],
          branchRate: [
            { validator: validatePercent, trigger: 'submitForm' }
          ],
          shareTitle: [
            { min: 0, max: 26, message: '长度在 0 到 26 个字符', trigger: 'blur' }
          ]
        },
        formLoading: false,
        btnLoading: false,
        isTeacher: false,
        stage1: [],
        stage2: [],
        BAST_API: process.env.BASE_API,
        teacherInfo: [],
        teacherList: [],
        imageUploadUrl: process.env.BASE_API + '/common/examTopic/imageUpload',
        avatarList: [],
        encodeUserId: null
        // imagecropperShow: false,
        // imagecropperKey: 0
      }
    },
    created() {
      this.getCompanyInfo()
      this.initData()
      this.getTeacher()
      this.enableSvip = enableSvip()
      console.log('dsdsada', this.enableSvip)
      if (this.postForm.hasteacher == -1) {
        this.isTeacher = false
      } else {
        this.isTeacher = true
      }
      this.stage1.push({
        firstRate: this.postForm.firstRate,
        secondRate: this.postForm.secondRate,
        thirdRate: this.postForm.thirdRate
      })
      this.stage2.push({
        dlsRate: this.postForm.dlsRate,
        partnerRate: this.postForm.partnerRate,
        branchRate: this.postForm.branchRate
      })
    },
    watch: {
      // 监听路由名称变化 重新调用数据
      $route: function(to, from) {
        if (to.name == 'editTopic') {
          this.initData()
        }
      }
    },
    methods: {
      // 方法
      initData() {
        if (this.isEdit) {
          this.formLoading = true
          const topicId = this.$route.params.id
          if (topicId) {
            getTopicDetail(topicId)
              .then(res => {
                this.postForm = res.data.data
                if (this.postForm.hasteacher == -1) {
                  this.isTeacher = false
                } else {
                  this.isTeacher = true
                }
                this.stage1 = []
                this.stage2 = []
                this.stage1.push({
                  firstRate: this.postForm.firstRate,
                  secondRate: this.postForm.secondRate,
                  thirdRate: this.postForm.thirdRate
                })
                this.stage2.push({
                  dlsRate: this.postForm.dlsRate,
                  partnerRate: this.postForm.partnerRate,
                  branchRate: this.postForm.branchRate
                })
                if (this.postForm.avatar) {
                  this.avatarList = [{ url: this.postForm.avatar }]
                }
                this.formLoading = false
                // 根据获取的teacherId查找出该讲师昵称
                // if (this.postForm.teacherId != 0) {
                getMemberSearch(this.postForm.encodeUserId).then(res => {
                  this.teacherInfo = res.data.data[0]
                }).catch(err => {
                  console.log(err)
                })
                // }
              })
              .catch(err => {
                console.log(err)
              })
          }
        }
      },
      isUpSelect(val) {
      },
      getTheTeacher(id) {
        getTheTea(id)
          .then(res => {
            // 正确回调
            this.teacherInfo['name'] = res.data.data[0].nickname
            this.teacherInfo['userId'] = res.data.data[0].userId
            this.teacherInfo['mobile'] = res.data.data[0].mobile
          })
          .catch(err => {
            console.log(err)
          })
      },
      isTeacherSelect(val) {
        if (val == 1) {
          this.isTeacher = true
        } else {
          this.isTeacher = false
        }
      }, // 是否关联讲师
      syncSearchTeachers(query) { // 获取讲师数据
        getMemberSearch(query).then(res => {
          this.syncLoading = false
          const resData = res.data.data
          this.teacherList = []
          for (let i = 0; i < resData.length; i++) {
            this.teacherList.push({
              userId: resData[i].userId,
              nickname: resData[i].nickname + `（ID: ${resData[i].encodeUserId}）`
            })
          }
        }).catch(err => {
          console.log(err)
        })
      },
      handleAvatarSuccess(response, file, fileList) {
        if (response.statusCode == 200) {
          this.postForm.avatar = response.data.imageUrl
          this.$message({
            message: '上传成功!',
            type: 'info'
          })
        } else {
          this.$message({
            message: '上传失败，请稍候再试!',
            type: 'info'
          })
        }
      },
      // // 图片裁剪
      // closeImageCropper() {
      //   this.imagecropperShow = false
      // },
      // cropSuccess(resData) {
      //   this.imagecropperShow = false
      //   this.imagecropperKey = this.imagecropperKey + 1
      //   this.postForm.avatar = resData.data.imageUrl
      // },
      submitForm() {
        // 提交表单
        var data = { topicArr: this.postForm }
        if (this.postForm.name == '') {
          this.$alert('名称不能为空！', '警告', {
            confirmButtonText: '确定'
          })
          return
        } else {
          if (this.postForm.name.length > 26) {
            this.$alert('名称长度不能超过26个字符！', '警告', {
              confirmButtonText: '确定'
            })
            return
          }
        }
        if (this.postForm.sort) {
          if (isNaN(this.postForm.sort)) {
            this.$alert('排序必须为纯数字！', '警告', {
              confirmButtonText: '确定'
            })
            return
          }
        }
        if (this.postForm.hasteacher == 1) {
          if (this.postForm.teacherId == '' || this.postForm.teacherId == null) {
            this.$message({
              message: '请选择讲师',
              type: 'error'
            })
            return
          }
        }
        if (this.postForm.price < 0 || this.postForm.sort < 0) {
          this.$message({
            message: '价格跟排序不能小于0',
            type: 'error'
          })
          return
        }
        if (this.postForm.vipDiscount < 0 || this.postForm.vipDiscount > 100 || this.postForm.svipDiscount < 0 || this.postForm.svipDiscount > 100) {
          this.$message({
            message: '会员折扣只能在0-100之间',
            type: 'error'
          })
          return
        }
        if (this.enableSvip) {
          if (Number(this.postForm.svipDiscount) > Number(this.postForm.vipDiscount)) {
            this.$notify({
              title: '提示',
              message: 'VIP折扣力度不能大于SVIP折扣！',
              type: 'warning'
            })
            return
          }
        }
        if (this.postForm.shareTitle) {
          if (this.postForm.shareTitle.length > 26) {
            this.$alert('名称长度不能超过26个字符！', '警告', {
              confirmButtonText: '确定'
            })
            return
          }
        }
        if (this.postForm.shareDesc) {
          if (this.postForm.shareDesc.length > 26) {
            this.$alert('描述不能超过29个字符！', '警告', {
              confirmButtonText: '确定'
            })
            return
          }
        }

        var countRate = 0
        this.postForm.firstRate = this.postForm.firstRate ? this.postForm.firstRate : 0
        this.postForm.secondRate = this.postForm.secondRate ? this.postForm.secondRate : 0
        this.postForm.thirdRate = this.postForm.thirdRate ? this.postForm.thirdRate : 0
        this.postForm.dlsRate = this.postForm.dlsRate ? this.postForm.dlsRate : 0
        this.postForm.partnerRate = this.postForm.partnerRate ? this.postForm.partnerRate : 0
        this.postForm.branchRate = this.postForm.branchRate ? this.postForm.branchRate : 0
        if (this.postForm.firstRate < 0 || this.postForm.firstRate > 100 || this.postForm.secondRate < 0 || this.postForm.secondRate > 100 || this.postForm.thirdRate < 0 || this.postForm.thirdRate > 100) {
          this.$message({
            type: 'warning',
            message: '抽成比例只能在0-100之际'
          })
          return
        }
        if (this.postForm.dlsRate < 0 || this.postForm.dlsRate > 100 || this.postForm.partnerRate < 0 || this.postForm.partnerRate > 100 || this.postForm.branchRate < 0 || this.postForm.branchRate > 100) {
          this.$message({
            type: 'warning',
            message: '抽成比例只能在0-100之际'
          })
          return
        }
        if (this.postForm.firstRate == 0) {
          if (this.postForm.secondRate != 0 || this.postForm.thirdRate != 0) {
            this.$message({
              type: 'warning',
              message: '第一级别抽成设置为0，第二三级只能设置为0'
            })
            return
          }
        }
        if (this.postForm.secondRate == 0) {
          if (this.postForm.thirdRate != 0) {
            this.$message({
              type: 'warning',
              message: '第二级别抽成设置为0，第三级只能设置为0'
            })
            return
          }
        }
        if (this.agentLevel == 0) {
          countRate = parseFloat(this.postForm.firstRate) + parseFloat(this.postForm.secondRate) + parseFloat(this.postForm.thirdRate)
        } else if (this.agentLevel == 1) {
          countRate = parseFloat(this.postForm.firstRate) + parseFloat(this.postForm.secondRate) + parseFloat(this.postForm.thirdRate) + parseFloat(this.postForm.dlsRate)
        } else if (this.agentLevel == 3) {
          countRate = parseFloat(this.postForm.firstRate) + parseFloat(this.postForm.secondRate) + parseFloat(this.postForm.thirdRate) + parseFloat(this.postForm.dlsRate) + parseFloat(this.postForm.partnerRate) + parseFloat(this.postForm.branchRate)
        }
        if (this.postForm.hasteacher) {
          this.postForm.teaRate = this.postForm.teaRate ? this.postForm.teaRate : 0
          countRate += parseFloat(this.postForm.teaRate)
          if (this.postForm.teaRate < 0) {
            this.$message({
              type: 'warning',
              message: '讲师抽成比例不能小于0'
            })
            return
          }
        }

        if (countRate > 100) {
          this.$notify({
            title: '提示',
            message: '所有分成比例之和不能超出100%!',
            type: 'warning'
          })
          return
        }
        if (this.postForm.teaRate < 0) {
          this.$notify({
            title: '提示',
            message: '讲师抽成比例不能小于0!',
            type: 'warning'
          })
          return
        }
        if (this.btnLoading) {
          return
        }
        this.btnLoading = true
        this.formLoading = true
        topicEditSave(data)
          .then(res => {
            this.formLoading = false
            this.btnLoading = false
            if (res.data.data.topicId) {
              this.postForm.topicId = res.data.data.topicId
            }
            this.$message({
              type: 'success',
              message: ' 保存成功! '
            })
            this.close()
          })
          .catch(err => {
            this.btnLoading = false
            this.formLoading = false
            console.log(err)
          })
      },
      getCompanyInfo() {
        toGetCompanyInfo(this.$route.params.columnId)
          .then(res => {
            this.agentLevel = res.data.data.agentLevels
          })
          .catch(err => {
            console.log(err)
          })
      },
      getTeacher() {
        initMemberList().then(res => {
          const resData = res.data.data
          this.teacherList = []
          for (let i = 0; i < resData.length; i++) {
            this.teacherList.push({
              userId: resData[i].userId,
              nickname: resData[i].nickname + `（ID: ${resData[i].encodeUserId}）`
            })
          }
        }).catch(err => {
          console.log(err)
        })
      },
      close() {
        this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
          const latestView = views.slice(-1)[0]
          const activeName = localStorage.getItem('testBar')
          if (latestView != null && latestView != '') {
            console.log('activeName', activeName)
            // if (activeName == 'first') {
            this.$router.push({ name: 'topics', params: { activeName: activeName }})
            // }
          } else {
            this.$router.push('/')
          }
        })
      },
      setDefultImg(e) {
        e.target.src = defultImg
      },
      handleBeforeUpload(file) {
        const isImg = file.type == 'image/jpeg' || file.type == 'image/png'
        if (!isImg) {
          this.$message.warning('上传图片只能是 JPG 或 PNG 格式')
        }
        const isLt3M = file.size / 1024 / 1024 < 3
        if (!isLt3M) {
          this.$message.error('上传图片大小不能超过 3MB!')
        }
        return isImg && isLt3M
      },
      submitAvatarUpload() {
        this.$refs.avatarUpload.submit()
      },
      teacherOptionSelect(selectedOption, id) {
        this.postForm.teacherId = selectedOption.userId
      },
      beforeChoose() {
        if (this.postForm.avatar != '') {
          this.$message.warning('请先清除已有图片再上传新图')
          return
        }
      }
    },
    mounted() {
      console.log(this.$route.params.id)
    }
  }
</script>
<style scoped>
</style>
